/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 01.06.2011, 01:34:08
 */

package de.realriu.snipzel.gui;

import de.realriu.riulib.gui.imagelist.AbstractImageList;
import de.realriu.riulib.gui.imagelist.ImageListAdapter;
import de.realriu.riulib.gui.imagelist.ReferenzImageList;
import de.realriu.snipzel.Main;
import de.realriu.snipzel.control.Controller;
import de.realriu.snipzel.model.CodeSnippet;
import de.realriu.snipzel.model.Comparators;
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JEditorPane;

/**
 *
 * @author riu
 */
public class MainFrame extends javax.swing.JFrame {

    Controller control = new Controller(this);
    private ReferenzImageList<CodeSnippet> snippet_list;

    /** Creates new form MainFrame */
    public MainFrame() throws IOException {
        super("SnipZel "+Main.VERSION);
        initComponents();
        snippet_list = (ReferenzImageList<CodeSnippet>)il_snippet_list;
        snippet_list.setVertikalTitlePosition(AbstractImageList.VertikalTitlePosition.AtBottom);
        snippet_list.setTitleColor(Color.BLACK);
        snippet_list.setHoverColor(Color.ORANGE);
        snippet_list.setSelectionColor(Color.BLUE);
        snippet_list.setSpaceBetweenPictures(20);
        snippet_list.setMargin(5, 5, 0, 0);
        snippet_list.setPadding(5, 5, 0, 10);
        snippet_list.addImageListListener(new ImageListAdapter<Image>() {
            @Override
            public void imageSelected(int pos) {
                if(pos!=-1) {
                    try {
                        control.loadSnippet(snippet_list.getReferenz(pos).getId(), false);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }

        });

        control.initWorkDirectory();
//        try {
//            CodeSnippet cs = new CodeSnippet(control.getNewSnippetID(), "blubb2", XhtmlRendererFactory.CPP ,"if(i>1000)\n{\n\texit();\n}", null);
//            control.saveSnippet(cs);
//            //ep_snippet_code.setPage(control.getURL(cs));
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        }

        //control.updateMyData();
    }

    public ReferenzImageList<CodeSnippet> getSnippet_list() {
        return snippet_list;
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        il_snippet_list = new ReferenzImageList<CodeSnippet>(AbstractImageList.Alignment.Vertical, false);
        tx_snippet_search = new javax.swing.JTextField();
        btn_add = new javax.swing.JButton();
        btn_remove = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ep_snippet_code = new javax.swing.JEditorPane();
        btn_edit = new javax.swing.JButton();
        btn_settings = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        il_snippet_list.setBackground(new java.awt.Color(255, 255, 255));

        org.jdesktop.layout.GroupLayout il_snippet_listLayout = new org.jdesktop.layout.GroupLayout(il_snippet_list);
        il_snippet_list.setLayout(il_snippet_listLayout);
        il_snippet_listLayout.setHorizontalGroup(
            il_snippet_listLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 121, Short.MAX_VALUE)
        );
        il_snippet_listLayout.setVerticalGroup(
            il_snippet_listLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 355, Short.MAX_VALUE)
        );

        tx_snippet_search.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                tx_snippet_searchCaretUpdate(evt);
            }
        });

        btn_add.setText("+");
        btn_add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_addActionPerformed(evt);
            }
        });

        btn_remove.setText("-");
        btn_remove.setEnabled(false);
        btn_remove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_removeActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        ep_snippet_code.setContentType("text/html");
        ep_snippet_code.setEditable(false);
        jScrollPane1.setViewportView(ep_snippet_code);

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 705, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE)
        );

        btn_edit.setText("edit");
        btn_edit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_editActionPerformed(evt);
            }
        });

        btn_settings.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/realriu/snipzel/resource/settings.png"))); // NOI18N
        btn_settings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_settingsActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(btn_add, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 44, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(tx_snippet_search, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
                    .add(il_snippet_list, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(btn_settings, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 44, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 546, Short.MAX_VALUE)
                        .add(btn_edit)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(btn_remove, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 44, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(tx_snippet_search, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(il_snippet_list, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btn_add)
                    .add(btn_remove)
                    .add(btn_edit)
                    .add(btn_settings))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_removeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_removeActionPerformed
        try {
            snippet_list.removeImage(snippet_list.indexOf(control.getCurrentSnippet()));
            control.deleteSnippet(control.getCurrentSnippet());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btn_removeActionPerformed

    private String lastSearch = "";

    private void tx_snippet_searchCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_tx_snippet_searchCaretUpdate
        String newSearch = tx_snippet_search.getText().trim();
        if(!lastSearch.equals(newSearch)){
            if(newSearch.equals("")){
                snippet_list.sort(new Comparators.AlphabeticTitleComparator(), true, 85, true, ReferenzImageList.SortAlgorithm.Quicksort);
            }else{
                snippet_list.sort(new Comparators.TitleAndTagSearchComparator(newSearch), true, 85, true, ReferenzImageList.SortAlgorithm.Quicksort);
            }
            lastSearch = newSearch;
            snippet_list.centerImage(0, 70);
        }
    }//GEN-LAST:event_tx_snippet_searchCaretUpdate

    private void btn_editActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_editActionPerformed
        CreateEditSnippet ces = new CreateEditSnippet(this, true, control);
        CodeSnippet toLoad;
        ces.setVisible(true);
        if(ces.isDoSave()){
            {
                toLoad = control.getCurrentSnippet();
                snippet_list.setTitle(snippet_list.indexOf(control.getCurrentSnippet()), control.getCurrentSnippet().getTitle());

                try {
                    snippet_list.replaceImage(snippet_list.indexOf(control.getCurrentSnippet()), (Image)control.getImageForLang(control.getCurrentSnippet().getLanguage()));
                    ep_snippet_code.setPage("file:///");
                    ep_snippet_code.setPage(control.getURL(control.getCurrentSnippet()));
                    //control.loadSnippet(control.getCurrentSnippet().getId(), false);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    System.exit(1);
                }
            }

            //snippet_list.selectImage(-1);
            //snippet_list.selectImage(snippet_list.indexOf(toLoad));
            try{
                control.loadSnippet(toLoad.getId(), false);
            }catch(Exception e){
                e.printStackTrace();
                System.exit(1);
            }
        }
    }//GEN-LAST:event_btn_editActionPerformed

    private void btn_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_addActionPerformed
        control.unloadSnippet();
        CreateEditSnippet ces = new CreateEditSnippet(this, true, control);
        CodeSnippet toLoad = null;
        ces.setVisible(true);
        if(ces.isNewSnippet()){
           toLoad = ces.getCreatedSnippet();
           snippet_list.addImage((Image)control.getImageForLang(ces.getCreatedSnippet().getLanguage()), ces.getCreatedSnippet().getTitle(), ces.getCreatedSnippet());
           snippet_list.selectImage(snippet_list.indexOf(ces.getCreatedSnippet()));
           snippet_list.centerImage(snippet_list.indexOf(ces.getCreatedSnippet()), 80);

        }
        try{
            control.loadSnippet(toLoad.getId(), false);
        }catch(Exception e){
            e.printStackTrace();
            System.exit(1);
        }
    }

    public JEditorPane getEp_snippet_code() {
        return ep_snippet_code;
    }

    public JButton getBtn_remove() {
        return btn_remove;
    }//GEN-LAST:event_btn_addActionPerformed

    private void btn_settingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_settingsActionPerformed
        new SettingDialog(this, true, control).setVisible(true);
    }//GEN-LAST:event_btn_settingsActionPerformed

    

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new MainFrame().setVisible(true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    System.exit(1);
                }
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_add;
    private javax.swing.JButton btn_edit;
    private javax.swing.JButton btn_remove;
    private javax.swing.JButton btn_settings;
    private javax.swing.JEditorPane ep_snippet_code;
    private javax.swing.JPanel il_snippet_list;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField tx_snippet_search;
    // End of variables declaration//GEN-END:variables

}
